<template>
  <div class="main">
    <!-- 检索区,查询表单 -->
    <div class="search">
      <!-- 表单组件 -->
      <el-form
          :inline="true"
          ref="searchFromRef"
          :model="pm"
          class="searchForm"
      >
        <!-- 表单项 -->
          <el-form-item label="植物名称:" style="width: 180px" prop="plantId">
            <el-select v-model="pm.plantId" placeholder="请选择植物编码">
              <el-option
                  v-for="plant in plantList"
                  :key="plant.plantId"
                  :label="plant.plantName"
                  :value="plant.plantId"
              />
            </el-select>
          </el-form-item>
        <!-- 表单项 -->
        <el-form-item label="养殖方式：" style="width: 200px" prop="methodName">
          <el-input placeholder="养殖方式名称：" v-model="pm.methodName" />
        </el-form-item>
        <el-form-item label="光照要求：" style="width: 200px" prop="lightRequirement">
          <el-input placeholder="输入光照要求：" v-model="pm.lightRequirement" />
        </el-form-item>
        <el-form-item label="土壤类型：" style="width: 200px" prop="soilType">
          <el-input placeholder="输入土壤类型：" v-model="pm.soilType" />
        </el-form-item>
      </el-form>

      <!-- 按钮 -->
      <el-button
          color="#909399"
          plain
          :icon="Search"
          @click="search"
          style="width: 75px"
      >查询</el-button
      >
      <el-button
          color="#e6a23c"
          plain
          :icon="Refresh"
          @click="resetSearch"
          style="width: 75px"
      >重置</el-button
      >
    </div>

    <!-- 操作区 -->
    <div class="action">
      <el-button
          color="#409eff"
          plain
          :icon="Plus"
          @click="add"
          style="margin-left: 10px"
      >新增</el-button
      >

      <el-button type="danger" plain :icon="Delete" @click="deleteAll"
      >批量删除</el-button
      >
    </div>

    <!-- 数据展示区 -->
    <div class="data">
      <!-- 表格 -->
      <div class="grid">
        <el-table
            :data="tableData"
            style="width: 100%"
            :header-cell-style="headerCellStyle"
            @row-click="rowClick"
            ref="tableRef"
        >
          <el-table-column
              type="selection"
              width="50"
              align="center"
              header-align="center"
          />
          <el-table-column
              prop="methodId"
              label="种植编号"
              width="90"
              align="center"
              header-align="center"
          />
          <el-table-column
              prop="plantInformation.plantName"
              label="植物名称"
              width="100"
              align="center"
              header-align="center"
          />
          <el-table-column
              prop="plantInformation.imagePath"
              label="植物图片"
              width="100"
              align="center"
              header-align="center"
          >
            <template #default="scope">
              <div
                  class="row-avatar"
                  :style="'background-image:url(' + scope.row.plantInformation.imagePath + ')'"
              ></div>
            </template>
          </el-table-column>
          <el-table-column
              prop="methodName"
              label="养殖方式"
              width="100"
              align="center"
              header-align="center"
              show-overflow-tooltip
          />
          <el-table-column
              prop="lightRequirement"
              label="光照要求"
              width="100"
              align="center"
              header-align="center"
              show-overflow-tooltip
          />
          <el-table-column
              prop="temperatureRange"
              label="温度范围"
              width="100"
              align="center"
              header-align="center"
              show-overflow-tooltip
          />
          <el-table-column
              prop="wateringFrequency"
              label="浇水频率"
              width="120"
              align="center"
              header-align="center"
              show-overflow-tooltip
          />
          <el-table-column
              prop="soilType"
              label="土壤类型"
              width="200"
              align="center"
              header-align="center"
              show-overflow-tooltip
          />
          <el-table-column
              prop="fertilizationMethod"
              label="施肥要求"
              width="200"
              align="center"
              header-align="center"
              show-overflow-tooltip
          />
          <el-table-column
              prop="description"
              label="养殖方式详细描述"
              width="200"
              align="center"
              header-align="center"
              show-overflow-tooltip
          />

          <el-table-column fixed="right" label="操作" min-width="200">
            <template #default="scope">
              <el-button
                  color="#409eff"
                  :icon="Edit"
                  style="width: 70px"
                  @click="edit(scope.row)"
                  plain
              >编辑</el-button
              >
              <el-button
                  type="danger"
                  plain
                  :icon="Delete"
                  @click="removeById(scope.row)"
                  style="width: 70px"
              >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-pageNum="pageInfo.pageNum"
            v-model:pageNum-size="pageInfo.size"
            :pageNum-sizes="[10, 15, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageInfo.total"
            background
            @change="paginate"
        />
      </div>
    </div>
  </div>
  <el-dialog
      v-model="show"
      :title="title"
      width="800"
      draggable
      :close-on-click-modal="false"
      @close="close"
  >
    <el-form ref="sfRef" :model="pfm" label-width="100" style="width: 100%; margin: 0 auto;">
      <el-row :gutter="20">
        <el-col :span="12">
            <!-- 表单项 -->
            <el-form-item label="植物名称:"  prop="plantId">
              <el-select v-model="pfm.plantId" placeholder="请选择植物编码">
                <el-option
                    v-for="plant in plantList"
                    :key="plant.plantId"
                    :label="plant.plantName"
                    :value="plant.plantId"
                />
              </el-select>
            </el-form-item>

          <el-form-item label="养殖方式:" prop="methodName">
            <el-input v-model="pfm.methodName" />
          </el-form-item>

          <el-form-item label="光照要求:" prop="lightRequirement">
            <el-input v-model="pfm.lightRequirement" />
          </el-form-item>

          <el-form-item label="养殖详细描述:" prop="description">
            <el-input type="textarea" v-model="pfm.description" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="温度范围:" prop="temperatureRange">
            <el-input type="text" v-model="pfm.temperatureRange" />
          </el-form-item>

          <el-form-item label="浇水频率:" prop="wateringFrequency">
            <el-input type="text" v-model="pfm.wateringFrequency" />
          </el-form-item>
          <el-form-item label="施肥要求:" prop="fertilizationMethod">
            <el-input type="text" v-model="pfm.fertilizationMethod" />
          </el-form-item>
          <el-form-item label="土壤类型:" prop="soilType">
            <el-input v-model="pfm.soilType" />
          </el-form-item>

        </el-col>
      </el-row>
    </el-form>

    <!-- 对话框按钮，#插槽: 组件空出来，允许用户更改组件内容。由组件使用者定义 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 新增 对话框 -->
</template>

<script setup>
import { reactive, ref } from "vue";
import { onMounted, toRaw, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Delete,
  Edit,
  Search,
  Share,
  Upload,
  Refresh,
  Plus,
} from "@element-plus/icons-vue";
import plantInformationApi from "@/api/PlantApi";
import cultivationMethodsApi from "@/api/PlantMethodApi";

//当组件挂载结束之后调用
onMounted(() => {
  search();
  document.title = "植物表型数据管理系统";
});

//响应式对象
const tableData = ref([]);
// 响应内容
//发送请求获取所有的植物数据
const plantList = ref([]);
plantInformationApi.findAll().then((result) => {
  if (result.code == 200) {
    plantList.value = result.data.records;
  }
});

function paginate() {
  search();
}

// 分页信息
const pageInfo = ref({
  pageNum: 1,
  size: 10,
  total: 0,
});

// 当页码和页码大小改变时触发

function search() {
  let params = pm.value; //查询条件
  cultivationMethodsApi
      .findAll(pageInfo.value.pageNum, pageInfo.value.size, params)
      .then((result) => {
        if (result.code == 200) {
          tableData.value = result.data.records;
          pageInfo.value.total = result.data.total;
          pageInfo.value.pageNum = result.data.pages;
          pageInfo.value.size = result.data.size;
        }
      });
}

// 搜索条表单双向数据绑定
const pm = ref({
  methodName: "",
  lightRequirement: "",
  temperatureRange: "",
  soilType:"",
  plantId: ""
});

// // 表单实例的引用
let searchFromRef;
function resetSearch() {
  // 重置查询表单
  searchFromRef.resetFields();
}
// 定义表格实例
let tableRef;
//当点击表格时触发
function rowClick(row) {
  tableRef.toggleRowSelection(row);
}

// 删除操作逻辑
function deleteAll() {
  // 从表格中选中的行
  let rows = tableRef.getSelectionRows();
  let ids = []; //id数组
  for (let row of rows) {
    ids.push(row.plantId);
  }
  //执行删除操作
  deleteById(ids);
}
//根据id数组批量删除
function deleteById(ids) {
  // 判断是否选中了要删除的记录
  if (ids.length == 0) {
    ElMessage({
      message: "请选中要删除的记录！",
      type: "warning",
    });
  } else {
    ElMessageBox.confirm("是否确定删除选中的记录吗？", "Warning", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      cultivationMethodsApi
          .removeAll(ids)
          .then((resp) => {
            if (resp.code == 200) {
              ElMessage({
                type: "success",
                message: "删除成功",
              });
              search(); //刷新
            }
          })
          .catch(() => {
            ElMessage({
              type: "info",
              message: "删除操作取消",
            });
          });
    });
  }
}
//  按id删除
function removeById(row) {
  let plant = toRaw(row);
  deleteById([plant.plantId]);
}

// 对话框是否显示
const show = ref(false);

// 定义对话框内容
const plainFormModel = ref({
  methodName: "",
  lightRequirement: "",
  temperatureRange: "",
  wateringFrequency:"",
  soilType:"",
  fertilizationMethod: "",
  description:"",
  plantId: ""
});
// 对话框内容别名
const pfm = plainFormModel;

// 对话框标题
const title = ref("新增植物信息");
// 弹出新增
function add() {
  show.value = true;
  title.value = "新增植物信息";
  let plaint = pfm.value;
  plaint.plantId = "";
}
// 提交表单
function submitForm() {
  let plaint = pfm.value;
  if (plaint.plantId !== "" ) {
    //修改
    submitEdit(plaint);
  } else {
    //新增
    submitAdd(plaint);
  }
}

// 新增逻辑
function submitAdd(plaint) {
  cultivationMethodsApi.save(plaint).then((resp) => {
    if (resp.code == 200) {
      ElMessage({
        type: "success",
        message: "新增成功",
      });
      search();
    } else {
      ElMessage({
        type: "error",
        message: resp.msg,
      });
    }
  });
  show.value = false;
}

let sfRef;
// 关闭对话框，重置表单
function close() {
  sfRef.resetFields();
}

// 修改操作
function edit(row) {
  let plant = toRaw(row);
  // 浅拷贝
  row = Object.assign({}, plant);
  show.value = true;
  title.value = "修改植物信息";
  // 下一个时间滴答中赋值
  nextTick(() => {
    pfm.value = row; //给新增/修改表单赋值
  });
}
// 提交表单执行逻辑
function submitEdit(plaint) {
  cultivationMethodsApi.update(plaint).then((resp) => {
    if (resp.code == 200) {
      ElMessage({
        type: "success",
        message: "修改成功",
      });
      search();
    } else {
      ElMessage({
        type: "error",
        message: resp.msg,
      });
    }
  });
  show.value = false;
}

//表头样式
function headerCellStyle() {
  return {
    background: " #f4f4f5",
    textAlign: "center",
    color: "#909399",
  };
}

// 切换状态
function switchChange2(row) {
  let plaint = toRaw(row);
  user.locked = user.locked === true ? 0 : 1;
  cultivationMethodsApi.updataByState(plaint).then((resp) => {
    if (resp.code == 200) {
      ElMessage({
        type: "success",
        message: "修改成功",
      });
      // plaint.locked = plaint.locked === 0 ? 1 : 0;
      search();
    } else {
      ElMessage({
        type: "error",
        message: resp.msg,
      });
      // 如果修改失败，需要将开关状态还原
      // plaint.locked = plaint.locked === 0 ? 1 : 0;
    }
  });
}

//头像上传成功时的回调函数
function avatarSuccess(resp, file) {
  if (resp.code == 200) {
    pfm.value.imagePath = resp.data;
  }
}


</script>

<style scoped>

.demo-form-inline {
  display: flex;
  align-items: center;
}
/* 定义不同状态下的 CSS 类 */
.el-switch-enabled {
  --el-switch-on-color: #13c75b;
  --el-switch-off-color: #13c75b;
}
.el-switch-disabled {
  --el-switch-on-color: #f56c6c;
  --el-switch-off-color: #f56c6c;
}
.pagination {
  margin-top: 20px;
}
.search {
  display: flex;
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 5px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.search > form .el-form-item {
  flex-grow: 1;
  margin-right: 10px;
  margin-bottom: 0;
}
.action {
  margin-top: 10px;
  width: 100%;
  display: flex;
  padding: 10px 0;
  border-radius: 5px;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.1);
}
.dialog-footer {
  margin-top: 20px;
}
.data {
  margin-top: 5px;
  padding: 15px 10px;
  border: 1px solid #ccc;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}


.avatar {
  width: 120px;
  height: 120px;
  border: 1px solid #ccc;
}

.avatar .icon {
  width: 120px;
  height: 120px;
}

.avatar .preview {
  width: 120px;
  height: 120px;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: contain;
}

.row-avatar {
  width: 50px;
  height: 50px;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: contain;
  margin: 0 auto;
  border-radius: 50%; /* 设置为50%使头像为圆形 */
  overflow: hidden; /* 防止图片在圆外显示 */
}
</style>
